package com.example.service;

import cn.hutool.core.util.StrUtil;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.exception.CoustomException;
import com.example.mapper.AdminMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {

    @Resource
    private AdminMapper adminMapper;

    public List<Admin> selectAll(Admin admin) {
        List<Admin> list = adminMapper.selectAll(admin);
        return list;
    }

    public Admin selectById(Integer id) {
        Admin admin = adminMapper.selectById(id);
        return admin;
    }

    public PageInfo<Admin> selectPage( Admin Admin,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(Admin);
        return PageInfo.of(list);
    }

    /**
     * 新增管理员
     */
    public void add(Admin Admin) {
        String username = Admin.getUsername();
        Admin dbAdmin = adminMapper.selectByUsername(username);
        if(dbAdmin != null){ //数据库存在这个账号
            throw new CoustomException("500","账号已存在");
        }
        if(StrUtil.isBlank(Admin.getPassword())){ //密码没填
            Admin.setPassword("admin"); //默认密码

        }
        if(StrUtil.isBlank(Admin.getName())){ //名字没填
            Admin.setName(Admin.getUsername()); //默认名称
        }
        //一定要设置角色
        Admin.setRole("ADMIN"); //管理员角色
        adminMapper.insert(Admin);
    }

    public void update(Admin Admin) {
        adminMapper.updateById(Admin);
    }

    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            this.deleteById(id);
        }
    }

    public Admin login(Account account) {
        String username = account.getUsername();
        Admin dbAdmin = adminMapper.selectByUsername(username);
        if(dbAdmin == null){ //没查询到用户,说明没有这个账号
            throw new CoustomException("500","账号不存在");
        }
        //数据库存在这个账号
        String password = account.getPassword();
        if(!dbAdmin.getPassword().equals(password)){
            throw new CoustomException("500","账号或密码错误");
        }
        return dbAdmin;
    }
    //修改密码
    public void updatePassword(Account account) {
        Integer id = account.getId();
        Admin admin = this.selectById(id);
        if (!admin.getPassword().equals(account.getPassword())) { //页面传来的原密码跟数据库密码相对比,不匹配就报错
            throw new CoustomException("500","对不起,原密码错误");
        }
        admin.setPassword(account.getNewPassword());//设置新密码
        this.update(admin);
    }


}
